package com.xindz.hgq.database.greendao.view;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.constant.TimeConstants;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.orhanobut.logger.Logger;
import com.xindz.hgq.R;
import com.xindz.hgq.adapter.SimpleAdapter;
import com.xindz.hgq.app.App;
import com.xindz.hgq.base.BaseTitleActivity;
import com.xindz.hgq.base.options.BaseActivityOptions;
import com.xindz.hgq.database.greendao.GdDataCacheManager;
import com.xindz.hgq.database.greendao.bean.DaoSession;
import com.xindz.hgq.database.greendao.bean.DataCacheBeanDao;
import com.xindz.hgq.database.greendao.bean.User;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @name HGQBase
 * @class name：com.xindz.hgq.database.greendao.view
 * @describe 数据缓存示例类
 * greenDao数据实体 实现Serializable 接口报错解决方法 https://blog.csdn.net/jabony/article/details/76212183
 * @anthor XINDZ
 * @time 2018/5/15 17:16
 * @change
 * @chang time
 * @class describe
 */
public class GdDataCacheActivity extends BaseTitleActivity {
    @BindView(R.id.bt_gd_add_data)
    Button btGdAddData;
    @BindView(R.id.bt_gd_read_data)
    Button btGdReadData;
    @BindView(R.id.bt_gd_delete_data)
    Button btGdDeleteData;
    @BindView(R.id.rcv_gd_dc)
    RecyclerView rcvGdDc;
    String key = "_User";
    @BindView(R.id.et_input_key)
    AppCompatEditText etInputKey;
    @BindView(R.id.bt_gd_delete_data_all)
    Button btGdDeleteDataAll;
    private ArrayList<String> dataList = new ArrayList<>();
    private SimpleAdapter simpleAdapter;
    private String objId;
    private int name = 0;
    private DataCacheBeanDao dataCachBeanDao;
    private DaoSession daoSession;
    private GdDataCacheManager dataCacheManager;

    @Override
    public BaseActivityOptions setOption() {
        return new BaseActivityOptions().openTitle();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gd_datacahe);
        ButterKnife.bind(this);
        rcvGdDc.setLayoutManager(new LinearLayoutManager(this));
        simpleAdapter = new SimpleAdapter(R.layout.item_simple, dataList);
        rcvGdDc.setAdapter(simpleAdapter);
        daoSession = App.app.getDaoSession();
        dataCachBeanDao = daoSession.getDataCacheBeanDao();

        dataCacheManager = GdDataCacheManager.getInstance(daoSession);


    }

    @OnClick({R.id.bt_gd_add_data, R.id.bt_gd_read_data, R.id.bt_gd_delete_data
            , R.id.bt_gd_delete_data_all})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_gd_add_data:
                User newUserOne = createNewUser();
                User newUserTwo = createNewUser();
                List<String> jsonList = new ArrayList<>();
                jsonList.add(JSON.toJSONString(newUserOne));
                jsonList.add(JSON.toJSONString(newUserTwo));
                if (dataCacheManager.saveDataCache(getInPutKey(), jsonList)) {
                    ToastUtils.showShort("添加缓存数据成功");
                } else {
                    ToastUtils.showShort("添加缓存数据失败");
                }
                break;
            case R.id.bt_gd_read_data:
                dataList.clear();
                daoSession.runInTx(new Runnable() {
                    @Override
                    public void run() {
                        String inPutKey = getInPutKey();
                        ArrayList<User> list = dataCacheManager.queryDataCache(inPutKey, User.class);
                        if (list != null && list.size() > 0) {
                            for (User user : list) {
                                if (user != null) {
                                    dataList.add("Key:" + inPutKey + "   Data:" + user.toString());
                                }
                            }

                            ToastUtils.showShort("读取缓存数据成功");
                        } else {
                            ToastUtils.showShort("读取缓存数据失败");
                        }
                        simpleAdapter.notifyDataSetChanged();
                    }
                });

                break;
            case R.id.bt_gd_delete_data:
                if (dataCacheManager.deleteByKey(getInPutKey())) {
                    ToastUtils.showShort("删除缓存数据成功");
                } else {
                    ToastUtils.showShort("删除缓存数据失败");
                }
                break;
            case R.id.bt_gd_delete_data_all:
                if (dataCacheManager.clearAllDataCache()) {
                    ToastUtils.showShort("删除全部缓存数据成功");
                } else {
                    ToastUtils.showShort("删除全部缓存数据失败");
                }
                break;
        }
    }

    private User createNewUser() {
        User user = new User();
        long timeMillis = System.currentTimeMillis();
        objId = timeMillis + "";
        user.setObjecId(objId);
        user.setUsername("第" + name + "次添加");
        user.setSex(1);
        name++;
        Date dateByNow = TimeUtils.getDateByNow(timeMillis, TimeConstants.MSEC);
        Logger.i("时间:" + dateByNow.toString());
        user.setBirthday(dateByNow);
        user.setMobilePhoneNumber("10086" + name);
        user.setAvatar("图片路径:" + name);
        user.setMobilePhoneVerified(false);
        return user;
    }

    private String getInPutKey() {
        String inPutKey = etInputKey.getEditableText().toString().trim();
        if ("".equals(inPutKey)) {
            inPutKey = key;
        }
        return inPutKey;
    }
}
